import com.intellij.formatting.WhiteSpace;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiBuilderFactory;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.IconLoader;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.formatter.JavadocWhiteSpaceFormattingStrategy;
import com.intellij.psi.formatter.WhiteSpaceFormattingStrategy;
import com.intellij.psi.formatter.WhiteSpaceFormattingStrategyFactory;
import com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextArea;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.table.JBListTable;
import com.thoughtworks.qdox.model.expression.Add;
import net.sf.jsqlparser.JSQLParserException;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author laberinto
 * @version 1.0
 * @date 2023/1/31 16:52
 * @package PACKAGE_NAME
 * @message \\TODO
 * (⌓‿⌓)
 */
public class AddNoteDialog extends DialogWrapper {
    /**
     * 标题输入框
     */
    private JTextArea etfTitle;
    private JBTable jbTable;
    /**
     * 内容输入框
     */
    private JTextArea etfMark;
    /**
     * 注释输入框
     */
    private JTextArea apiMark;

    private Project myProject;
    private PsiFile myPsiFile;
    private Editor myEditor;
    private PsiClass myPsiClass;
    private  List<String> fileList=new ArrayList<>();
    String[] columnNames = {"FIELD","导出", "等于", "LIKE", "大于", "小于"};

    public AddNoteDialog(Project project,PsiFile psiFile,Editor editor,PsiClass psiClass) {
        super(true);
        myProject=project;
        myPsiFile=psiFile;
        myEditor=editor;
        myPsiClass=psiClass;
        setTitle("Sql转换成DTO");
        init();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        JPanel panel = new JPanel(new BorderLayout(5,5));
        //划分三块区域
        JLabel jLabel=new JLabel("SQL");
        JLabel jLabel1=new JLabel("DTO");
        JLabel jLabel2=new JLabel("注释");

        etfTitle = new JTextArea();
        Border border = BorderFactory.createLineBorder(Color.gray);
        etfTitle.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        etfMark = new JTextArea();
        etfMark.setAutoscrolls(true);
        etfMark.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        apiMark = new JTextArea();
        apiMark.setAutoscrolls(true);
        apiMark.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        //初始化表格
        jbTable=new JBTable();
        initTable(new Object[][]{});

        JPanel jPanel1=new JPanel(new BorderLayout(5,5));
        jPanel1.setPreferredSize(new Dimension(400,800));
        jPanel1.add(jLabel, BorderLayout.NORTH);

        JBScrollPane scrollPane = new JBScrollPane(
                etfTitle,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
        );

        jPanel1.add(scrollPane, BorderLayout.CENTER);


        JPanel jPanel2=new JPanel(new BorderLayout(5,5));
        jPanel2.setPreferredSize(new Dimension(700,800));
        jPanel2.add(jLabel1, BorderLayout.NORTH);
        JBScrollPane scrollPane2 = new JBScrollPane(
                jbTable,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
        );
        jPanel2.add(scrollPane2, BorderLayout.CENTER);

        JPanel jPanel3=new JPanel(new BorderLayout(5,5));
        jPanel3.setPreferredSize(new Dimension(100,800));
        jPanel3.add(jLabel2, BorderLayout.NORTH);
        JBScrollPane scrollPane3 = new JBScrollPane(
                apiMark,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
        );
        jPanel3.add(scrollPane3, BorderLayout.CENTER);


        panel.add(jPanel1, BorderLayout.WEST);
        panel.add(jPanel2, BorderLayout.EAST);
        panel.add(jPanel3,BorderLayout.CENTER);

        return panel;
    }

    private void initTable(Object[][] data) {

        TableModelProxy tableModel = new TableModelProxy(columnNames, data);
        jbTable.setModel(tableModel);
        jbTable.getTableHeader().setDefaultRenderer(new CheckHeaderCellRenderer(jbTable));
        jbTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellTextAreaRenderer());
        jbTable.setRowHeight(50);
        jbTable.getColumnModel().getColumn(0).setPreferredWidth(300);
        jbTable.getColumnModel().getColumn(1).setPreferredWidth(70);
        jbTable.getColumnModel().getColumn(2).setPreferredWidth(70);
        jbTable.getColumnModel().getColumn(3).setPreferredWidth(70);
        jbTable.getColumnModel().getColumn(4).setPreferredWidth(70);
        jbTable.getColumnModel().getColumn(5).setPreferredWidth(70);
    }

    @Override
    protected JComponent createSouthPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        JButton btnAdd = new JButton("立即转换");
        JButton btnCom = new JButton("确认");
        //按钮点击事件处理
        btnAdd.addActionListener(e -> {
            //获取标题
           // model.getDataVector().clear();
            String name = etfTitle.getText();
            String apiName = apiMark.getText();
            if ("".equals(name)){
                Messages.showMessageDialog(myProject,
                        "请先输入SQL",
                        "提示", Messages.getErrorIcon());
                return;
            }

            try {
                fileList= SqlParserTool.getSelectColumnName(name);
            } catch (JSQLParserException jsqlParserException) {
                jsqlParserException.printStackTrace();
            }

            String[] split = apiName.split("\n");
            StringBuffer sb=new StringBuffer();
            int i=0;
            List<List<Object>> list = new ArrayList();
            for (String columnName:fileList){
                columnName = CaseUtils.convertToCamelCase(columnName);
                String y ="";

                if (split.length>i){
                     y = "\n@ApiModelProperty(value = \""+split[i]+"\")\n" +
                            "private String " + columnName + ";\n";
                }else {
                    y = "\n@ApiModelProperty(value = \"\")\n" +
                            "private String " + columnName + ";\n";
                }
                List<Object> list1=new ArrayList<>();
                list1.add(y);
                list1.add(false);
                list1.add(false);
                list1.add(false);
                list1.add(false);
                list1.add(false);
                list.add(list1);
                i++;
            }
            Object[][] res = new Object[list.size()][]; // 存放转换结果的 二维数组
            for(int i1=0; i1<res.length; i1++){ // 转换方法
                res[i1] = list.get(i1).toArray(new Object[list.get(i1).size()]);
            }
           initTable(res);
        });
        //按钮点击事件处理
        btnCom.addActionListener(e -> {

            //获取内容
            TableModelProxy model = (TableModelProxy) jbTable.getModel();
            Object[][] data = model.getData();
            String content = apiMark.getText();
            String[] split = content.split("\n");

            WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
                @Override
                public void run() {
                    int i=0;
                    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);

                    PsiType psiType = PsiType.getTypeByName("String", myProject
                            , GlobalSearchScope.EMPTY_SCOPE);
                    PsiType psiType2 = PsiType.getTypeByName("Long", myProject
                            , GlobalSearchScope.EMPTY_SCOPE);
                    PsiType psiType3 = PsiType.getTypeByName("BigDecimal", myProject
                            , GlobalSearchScope.EMPTY_SCOPE);
                    StringBuffer text=new StringBuffer();
                    text.append("/*\n");
                    for(String file :fileList){

                        PsiField psiField=null;
                        PsiField psiField1=null;
                        PsiField psiField2=null;
                        String fileOld=file;
                        file = CaseUtils.convertToCamelCase(file);
                        if (file.contains("Id")||file.contains("id")){
                             psiField = elementFactory.createField(file, psiType2);

                        }else if (file.contains("Qty")||file.contains("Number")||file.contains("Weight")||file.contains("qty")||file.contains("number")||file.contains("weight")){
                            psiField = elementFactory.createField(file, psiType3);
                        }else {
                            psiField = elementFactory.createField(file, psiType);
                        }

                        if (data.length>i) {
                            Object[] datum = data[i];

                            if ((boolean)datum[2]){
                                text.append("<if test=\"dto."+file+" != null and dto."+file+" != '' \">\n");
                                text.append("   AND t."+fileOld+" = #{dto."+file+"}\n");
                                text.append("</if>\n");
                            }
                            if ((boolean)datum[3]){
                                text.append("<if test=\"dto."+file+" != null and dto."+file+" != '' \">\n");
                                text.append("   AND t."+fileOld+" like CONCAT('%',#{dto."+file+"},'%')\n");
                                text.append("</if>\n");
                            }
                            if ((boolean)datum[4]){
                                psiField1 = elementFactory.createField(file+"From", psiType);

                                if (split.length > i) {
                                    psiField1.getModifierList().addAnnotation("ApiModelProperty(value = \"" + split[i] + "从\")");
                                }else {
                                    psiField1.getModifierList().addAnnotation("ApiModelProperty(value = \"" + "XX时间从\")");
                                }
                                //myPsiClass.add(psiField1);
                                text.append("<if test=\"dto."+file+"From"+" != null and dto."+file+"From"+" != '' \">\n");
                                text.append("   AND t."+fileOld+" &gt;= #{dto."+file+"From"+"}\n");
                                text.append("</if>\n");
                            }
                            if ((boolean)datum[5]){
                                psiField2 = elementFactory.createField(file+"To", psiType);
                                if (split.length > i) {
                                    psiField2.getModifierList().addAnnotation("ApiModelProperty(value = \"" + split[i] + "至\")");
                                }else {
                                    psiField2.getModifierList().addAnnotation("ApiModelProperty(value = \"" + "XX时间至\")");
                                }
                                //myPsiClass.add(psiField2);
                                text.append("<if test=\"dto."+file+"To"+" != null and dto."+file+"To"+" != '' \">\n");
                                text.append("   AND t."+fileOld+" &lt;= #{dto."+file+"To"+"}\n");
                                text.append("</if>\n");
                            }

                            if (split.length > i) {
                                if ((boolean) datum[1]) {
                                    psiField.getModifierList().addAnnotation("ExcelColumn(zh =  \"" + split[i] + "\", en = \"" + file + "\", order = 1)");
                                }
                                psiField.getModifierList().addAnnotation("ApiModelProperty(value = \"" + split[i] + "\")");
                            }else {

                                if ((boolean) datum[1]) {
                                    psiField.getModifierList().addAnnotation("ExcelColumn(zh =  \"\", en = \"" + file + "\", order = 1)");
                                }
                                psiField.getModifierList().addAnnotation("ApiModelProperty(value = \"\")");

                            }


                        }

                        myPsiClass.add(psiField);

                        if (psiField1!=null){
                            myPsiClass.add(psiField1);
                        }
                        if (psiField2!=null){
                            myPsiClass.add(psiField2);
                        }

                        i++;
                    }
                    text.append("*/");
                    if (text.toString().length()>10){
                        PsiComment commentFromText = elementFactory.createCommentFromText(text.toString(), myPsiClass);
                        myPsiClass.add(commentFromText);
                    }

                    CodeStyleManager.getInstance(myProject).reformat(myPsiClass);
                }
            });
            close(0);
        });
        panel.add(btnAdd);
        panel.add(btnCom);
        return panel;/* eewrwer*/
    }
}
/*
<if test="dto.shortName != null and dto.shortName != '' ">
        AND hlb.SHORT_NAME like CONCAT('%',#{dto.shortName},'%')
</if>

 */


